<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="4" :sm="24">
              <a-form-item label="设备编号">
                <a-input v-model="queryParam.equipmentNo" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="报警名称">
                <a-input v-model="queryParam.name" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="no" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="name" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="equipmentNo" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="alarmType" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="memberId" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="email" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="phone" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="highTemperature" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="lowTemperature" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="status" slot-scope="text">
          <!-- <a-badge :status="text" /> -->
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)"><a-icon type="edit"/></a>
            <a-divider type="vertical" />
            <a @click="handleDeleteOk(record.id)"><a-icon type="delete"/></a>
            <!-- <a @click="handleEdit(record)">配置</a>
            <a @click="handleSub(record)">订阅报警</a> -->
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { deletePhotovoltaicAlarmSetting, updatePhotovoltaicAlarmSetting, createPhotovoltaicAlarmSetting, getAlarmById, getPhotovoltaicAlarmSetting } from '@/api/alarm'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateAlarm'
import { create } from 'lodash'

const columns = [
  {
    title: 'ID',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '报警名称',
    dataIndex: 'name'
  },
  {
    title: '设备编号',
    dataIndex: 'equipmentNo'
  },
  {
    title: '报警类型',
    dataIndex: 'alarmType'
  },
  {
    title: 'email',
    dataIndex: 'email'
  },
  {
    title: '高于温度报警',
    dataIndex: 'highTemperature'
  },
  {
    title: '低于温度报警',
    dataIndex: 'lowTemperature'
  },
  {
    title: '发送用户',
    dataIndex: 'memberId'
  },
  {
    title: '密码',
    dataIndex: 'password'
  },
  {
    title: '发送手机号',
    dataIndex: 'phone'
  },
  {
    title: '备注',
    dataIndex: 'remark'
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    text: '正常'
  },
  1: {
    text: '停用'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getPhotovoltaicAlarmSetting(requestParameters)
          .then(res => {
            const data = res.data
            data.list.forEach(element => {
              element.status = element.status == 0 ? '正常' : '停用'
              element.alarmType = element.alarmType == 1 ? '太阳能' : '继电器'
            })
            return data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      groupList: []
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    }
  },
  created () {
    this.getGroupList()
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    getGroupList () {
      var params = {
        pageNum: 1,
        pageSize: 100
      }
      getDeviceGroupList(params).then(res => {
        this.groupList = res.data.list
        console.log('groupList', this.groupList)
      })
    },
    handleDeleteOk (id) {
      var that = this
      this.$confirm({
        title: '确认要删除吗',
        onOk () {
          deletePhotovoltaicAlarmSetting(id).then(res => {
            if (res.code == 200) {
              // 刷新表格
              that.$refs.table.refresh(true)
              that.$message.info('删除成功')
            } else {
              that.$message.error(res.message)
            }
          })
        },
      onCancel () {}
      })
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      console.log('1', record)
      this.mdl = { ...record }
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          // 正则匹配手机号码和邮箱
          if (values.phone) {
            var reg = /^1[3456789]\d{9}$/
            if (!reg.test(values.phone)) {
              this.$message.error('手机号码格式不正确')
              this.confirmLoading = false
              return
            }
          }
          if (values.email) {
            var reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
            if (!reg.test(values.email)) {
              this.$message.error('邮箱格式不正确')
              this.confirmLoading = false
              return
            }
          }
          if (values.id > 0) {
            updatePhotovoltaicAlarmSetting(values).then(res => {
              console.log('res', res)
              this.confirmLoading = false
              // 刷新表格
              this.$refs.table.refresh()
              if (res.code == 200) {
                // 重置表单数据
                this.visible = false
                form.resetFields()
                this.$message.info('修改成功')
              } else {
                this.$message.err(res.message)
              }
            })
          } else {
            // 新增
            createPhotovoltaicAlarmSetting(values).then(res => {
              console.log('res', res)
              this.confirmLoading = false
              // 刷新表格
              this.$refs.table.refresh()
              if (res.code == 200) {
                // 重置表单数据
                this.visible = false
                form.resetFields()
                this.$message.info('新增成功')
              } else {
                this.$message.error(res.message)
              }
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
